package com.amtf.datafile3.core.fil;

import java.io.File;

import com.amtf.datafile3.DataCatalog;
import com.amtf.datafile3.DataException;
import com.amtf.datafile3.DataFile;
import com.amtf.datafile3.DataTableDefinition;
import com.amtf.datafile3.DefinitionException;
import com.amtf.datafile3.cfg.fil.FilDataTableDefinition;

public class FilDataFile extends DataFile {
	private static final long serialVersionUID = -7200875452550106437L;
	private int startRow;
	private boolean firstRowTitle;
	private String charset;
	private int[] eachColumnLength = null;

	public FilDataFile(File fileOrDir, String charset, boolean firstRowTitle, int[] eachColumnLength) {
		this(fileOrDir, charset, 0, firstRowTitle, eachColumnLength);
	}

	public FilDataFile(File fileOrDir, String charset, int startRow, boolean firstRowTitle, int[] eachColumnLength) {
		super(null, fileOrDir);
		this.dataAccessor = new FilDataAccessor();
		this.charset = charset;
		this.startRow = startRow;
		this.firstRowTitle = firstRowTitle;
		this.eachColumnLength = eachColumnLength;
	}

	public FilDataFile(DataTableDefinition definition, File fileOrDir) throws DefinitionException {
		super(definition, fileOrDir);

		if (!(definition instanceof FilDataTableDefinition)) {
			throw new DefinitionException("Definition must be instance of FilDataTableDefinition");
		} else {
			this.dataAccessor = new FilDataAccessor();

			FilDataTableDefinition def = (FilDataTableDefinition) definition;
			this.charset = def.getCharset();
			this.startRow = def.getStartRow();
			this.firstRowTitle = def.isFirstRowTitle();
		}
	}

	public DataCatalog openCatalog() throws DataException {
		DataCatalog dc = dataAccessor.open("file:///" + this.getPath() + "?charset=" + charset + "&startRow=" + startRow + "&firstRowTitle=" + firstRowTitle + "&columnsLength="
				+ FilDataAccessor.columnsLength2String(eachColumnLength) + "&filePattern=*.fil&subFolder=false");
		if (definition != null) {
			dc.setDataTableDefinition(definition);
		}
		return dc;
	}
}
